<%@ Page Language="C#" MasterPageFile="~/Site.master" Title="DataList Editing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">

<script src="../jquery/jquery-1.2.6.min.js" language="javascript"></script>
    <script src="../jquery/jquery-ui-personalized-1.6rc2.min.js" language="javascript"></script>
    <table>
        <tr>
            <td style="text-align:left">
                <AjaxData:DataList ID="DataList1" runat="server" DataKeyField="ID" CssClass="DataWebControlStyle" ShowHeader="false"
                    AllowDragAndDrop="true" EditCommandEvent="onEditCommand" DeleteCommandEvent="onDeleteCommand" ItemDataBoundEvent="onItemDataBound"
                    UpdateCommandEvent="onUpdateCommand" CancelCommandEvent="onCancelCommand"  ItemDragStartEvent="onItemDragStart" 
                    ItemDroppedEvent="onItemDropped">
                   <AlternatingItemStyle CssClass="AlternatingRowStyle" />
                   <ItemStyle CssClass="RowStyle" />
                   <HeaderStyle CssClass="HeaderStyle" />
                   <FooterStyle CssClass="FooterStyle" />
                   <HeaderTemplate><h3>Product Information</h3></HeaderTemplate>
                    <ItemTemplate>
                        <h4>
                            {{ Eval(Name) }}
                        </h4>
                        <table border="0">
                            <tr>
                                <td class="ProductPropertyLabel">Category:</td>
                                <td>{{ Eval(CategoryName) }}</td>
                                <td class="ProductPropertyLabel">Supplier:</td>
                                <td>{{ Eval(SupplierName) }}</td>
                            </tr>
                            <tr>
                                <td class="ProductPropertyLabel">Discontinued:</td>
                                <td>{{ Eval(Discontinued) }}</td>
                                <td class="ProductPropertyLabel">Price:</td>
                                <td>{{ Eval(UnitPrice) }}</td>
                            </tr>
                            <tr>
                                <td colspan="4">
                                    <input id="btnEdit" type="button" value="Edit" commandName="edit" />
                                    <input id="btnDelete" type="button" value="Delete" commandName="delete" />
                                </td>
                            </tr>
                        </table>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <h4>
                            <span id="spnProductName"></span>
                        </h4>
                        <table border="0">
                            <tr>
                                <td class="ProductPropertyLabel">Name:</td>
                                <td colspan="3" class="ProductPropertyValue">
                                    <input id="txtName" type="text" value="{{ Eval(Name) }}" />
                                </td>
                            </tr>
                            <tr>
                                <td class="ProductPropertyLabel">Category:</td>
                                <td class="ProductPropertyValue">
                                    <select id="ddlCategory" ></select>
                                </td>
                                <td class="ProductPropertyLabel">Supplier:</td>
                                <td>
                                    <select id="ddlSupplier"></select>
                                </td>
                            </tr>
                            <tr>
                                <td class="ProductPropertyLabel">Discontinued:</td>
                                <td class="ProductPropertyValue">
                                    <input id="chkDiscontinued" type="checkbox" {{ Eval(Discontinued) == true ? 'checked' : '' }} />
                                </td>
                                <td class="ProductPropertyLabel">Price:</td>
                                <td class="ProductPropertyValue">
                                    {{ Eval(UnitPrice) }}
                                </td>
                            </tr>
                            <tr>
                                <td colspan="4">
                                    <input id="btnUpdate" type="button" value="Update" commandName="update" />&nbsp;
                                    <input id="btnCancel" type="button" value="Cancel" commandName="cancel" />
                                </td>
                            </tr>
                        </table>
                    </EditItemTemplate>
                    <SeparatorTemplate>
                        <hr />
                    </SeparatorTemplate>
                    <FooterTemplate>
                        <p>
                            Footer
                        </p>
                    </FooterTemplate>
                </AjaxData:DataList>
            </td>
        </tr>
        <tr>
            <td style="text-align:right">
                <AjaxData:Pager ID="Pager1" PageSize="3" runat="server" CssClass="PagerRowStyle" CurrentPageStyle-CssClass="PagerCurrentPage" OtherPageStyle-CssClass="PagerOtherPage" PageChangedEvent="pageChanged"></AjaxData:Pager>
            </td>
        </tr>
    </table>
    <div id="divEvents" class="trace"></div>
    <script type="text/javascript">

        var _dataList;
        var _pager;

        var _categories;
        var _suppliers;
        var _products;

        function pageLoad(sender, e)
        {
            _dataList = DataList1;
            _pager = Pager1;

            DataService.GetAllCategory(function(categories){_categories = categories});
            DataService.GetAllSupplier(function(suppliers){_suppliers = suppliers});
            loadProducts();
        }

        function loadProducts()
        {
            var startIndex = (_pager.get_pageIndex() * _pager.get_pageSize());

            DataService.GetProductList(startIndex, _pager.get_pageSize(), '', '', onProductLoadSuccess);
        }

        function onProductLoadSuccess(result)
        {
            _products = result.Rows;
            _pager.set_recordCount(result.Total);
            
            bindProducts();
        }

        function bindCategories(categoryDropDownList)
        {
            clearListBox(categoryDropDownList);
            addListBoxItem(categoryDropDownList, '[none]', -1);

            if (_categories)
            {
                for(var i = 0; i < _categories.length; i++)
                {
                    addListBoxItem(categoryDropDownList, _categories[i].Name, _categories[i].ID);
                }
            }
        }

        function bindSuppliers(supplierDropDownList)
        {
            clearListBox(supplierDropDownList);
            addListBoxItem(supplierDropDownList, '[none]', -1);

            if (_suppliers)
            {
                for(var i = 0; i < _suppliers.length; i++)
                {
                    addListBoxItem(supplierDropDownList, _suppliers[i].Company, _suppliers[i].ID);
                }
            }
        }

        function bindProducts()
        {
            _dataList.set_dataSource(_products);
            _dataList.dataBind();
        }

        function onItemDataBound(sender, e)
        {
            var item = e.get_item();

            if (item.get_isDataItemType())
            {
                var product = item.get_dataItem();

                if (item.get_itemType() == AjaxDataControls.DataListItemType.EditItem)
                {
                    var ddlCategory = item.findControl('ddlCategory');
                    var ddlSupplier = item.findControl('ddlSupplier');
                    
                    bindCategories(ddlCategory);
                    selectListBoxByValue(ddlCategory, product.CategoryID);

                    bindSuppliers(ddlSupplier);
                    selectListBoxByValue(ddlSupplier, product.SupplierID);
                }                
            }
        }

        function onEditCommand(sender, e)
        {
            _dataList.set_editItemIndex(e.get_item().get_itemIndex());
        }

        function onDeleteCommand(sender, e)
        {
            if (confirm('Are you sure you want to delete this product?'))
            {
                var productId = _dataList.get_dataKeys()[e.get_item().get_itemIndex()];

                DataService.DeleteProduct(
                                            productId,
                                            function(result)
                                            {
                                                if (result == true)
                                                {
                                                    _dataList.set_editItemIndex(-1);
                                                    loadProducts();
                                                }
                                            }
                                          );
            }
        }

        function onUpdateCommand(sender, e)
        {
            var item = e.get_item();

            var productId = _dataList.get_dataKeys()[e.get_item().get_itemIndex()];
            var txtName = item.findControl('txtName');
            var ddlCategory = item.findControl('ddlCategory');
            var ddlSupplier = item.findControl('ddlSupplier');
            var chkDiscontinued = item.findControl('chkDiscontinued');

            var product = e.get_item().get_dataItem();

            product.Name = txtName.value.trim();
            product.CategoryID = parseInt(ddlCategory.options[ddlCategory.selectedIndex].value);

            if (product.CategoryID < 1)
            {
                product.CategoryName = '';
            }
            else
            {
                product.CategoryName = ddlCategory.options[ddlCategory.selectedIndex].text;
            }

            product.SupplierID = parseInt(ddlSupplier.options[ddlSupplier.selectedIndex].value);

            if (product.SupplierID < 1)
            {
                product.SupplierName = '';
            }
            else
            {
                product.SupplierName = ddlSupplier.options[ddlSupplier.selectedIndex].text;
            }

            product.Discontinued = chkDiscontinued.checked;

            DataService.UpdateProduct(
                                        productId,
                                        product.Name,
                                        product.CategoryID,
                                        product.SupplierID,
                                        product.Discontinued,
                                        function(result)
                                        {
                                            if (result == true)
                                            {
                                                _dataList.set_editItemIndex(-1);
                                            }
                                        }
                                      );
        }

        function onCancelCommand(sender, e)
        {
            _dataList.set_editItemIndex(-1);
        }

        function onItemDragStart(sender, e)
        {
            var item = e.get_item();

            writeMessage(String.format('Item {0} Drag Started<br/>', item.get_itemIndex()));
        }

        function onItemDropped(sender, e)
        {
            var item = e.get_item();

            writeMessage(String.format('Item Dropped in index {0} from index {1}<br/>', e.get_newIndex(), e.get_oldIndex()));
        }

        function pageChanged(sender, e)
        {
            _dataList.set_editItemIndex(-1);
            _pager.set_pageIndex(e.get_newPageIndex());
            loadProducts();
        }

        function writeMessage(message)
        {
            $get('divEvents').innerHTML += message;
        }

        function clearListBox(listBox)
        {
            for (var i = listBox.childNodes.length - 1; i > -1; i--)
            {
                listBox.removeChild(listBox.childNodes[i]);
            }
        }

        function addListBoxItem(listBox, text, value)
        {
            var opt = document.createElement('option');

            listBox.appendChild(opt);

            setText(opt, text);

            if (value != null)
            {
                opt.value = value;
            }
        }

        function selectListBoxByValue(listBox, value)
        {
            listBox.selectedIndex = 0;

            var length = listBox.options.length;

            for (var i = 0; i < length; i++)
            {
                if (listBox.options[i].value == value)
                {
                    listBox.selectedIndex = i;
                    break;
                }
            }
        }

        function setText(element, text)
        {
            if (typeof element.textContent != 'undefined')
            {
                element.textContent = text;
            }
            else if (typeof element.innerText != 'undefined')
            {
                element.innerText = text;
            }
        }

    </script>
</asp:Content>